package com.dirk.happie.activities;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.beans.ArticleBean;
import com.dirk.happie.beans.SettingsBean;
import com.dirk.happie.fragments.CompanyFragment;
import com.dirk.happie.network.GetHistoryTask;
import com.dirk.happie.network.GetOffersTask;
import com.dirk.happie.network.GetSettingsTask;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.widgets.NavigationBarView;

public class MenuActivity extends FragmentActivity {

	private View linearBottom;

	MyAdapter mAdapter;
	PageListener listener;
	ViewPager mPager;

	private Button orderNowButton;
	private Button specialOfferButton;
	private Button orderHistoryButton;

	private GetSettingsTask getSettingsTask = null;
	private GetOffersTask getOffersTask = null;

	private App mApp;
	private NavigationBarView navigation;

	private final String LOG_TAG = MenuActivity.class.getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);
		this.mApp = ((App) getApplication());
		// Keys.prefs = getSharedPreferences(Keys.happieapp_prefs,
		// MODE_PRIVATE);
		navigation = (NavigationBarView) findViewById(R.id.navigation);

		createCompanyLayout();

		buttonListeners();

		// Intent intent = new Intent();
		// intent.setAction("com.dirk.happie.utils.ApplicationReceiver");
		// intent.putExtra("referrer", "referrer");
		// sendBroadcast(intent);

		footerMenuListeners();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// System.out.println(mApp.isLoggedIn());
		if (mApp.isLoggedIn()) {
			linearBottom.setVisibility(View.VISIBLE);
		} else {
			linearBottom.setVisibility(View.GONE);
		}
		if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
			listener.onPageSelected(mApp.getPosition());
			mApp.setCompanyLogo(mApp.getFavorites().get(mApp.getPosition()).getCompanyLogo());
			mApp.setCompanyId(mApp.getFavorites().get(mApp.getPosition()).getCompanyId());
			navigation.setCount(mApp.getFavorites().size());
			navigation.setPos(mApp.getPosition());
			// getSettings();
			// getOffers();
		} else {
			navigation.setCount(0);
			navigation.setPos(mApp.getPosition());
		}
		showNavigation();
	}

	public class MyAdapter extends FragmentPagerAdapter {
		private SparseArray<CompanyFragment> fragmentsList = new SparseArray<CompanyFragment>();

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Log.d(LOG_TAG, "instantiate item " + position);
			return super.instantiateItem(container, position);
		}

		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) ? mApp.getFavorites().size() : 1;
		}

		@Override
		public Fragment getItem(int position) {
			CompanyFragment companyFragment = fragmentsList.get(position);
			if (companyFragment == null) {
				companyFragment = new CompanyFragment();
				Bundle data = new Bundle();
				data.putInt("current_page", position);
				companyFragment.setArguments(data);
				fragmentsList.append(position, companyFragment);
			}
			return companyFragment;

		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

	}

	private class PageListener extends SimpleOnPageChangeListener {
		public void onPageSelected(int position) {
			mApp.setPosition(position);
			mApp.getHappie_prefs().edit().putInt("Postion", position).commit();
			navigation.setPos(position);
			showNavigation();
			// System.out.println("position = " + mApp.position);
			if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
				mApp.setCompanyId(mApp.getFavorites().get(position).getCompanyId());
			}
			mApp.setCompanyLogo((mApp.getFavorites().get(mApp.getPosition()).getCompanyLogo()));
			getSettings();
			getOffers();
		}
	}

	private void createCompanyLayout() {

		mAdapter = new MyAdapter(getSupportFragmentManager());
		listener = new PageListener();

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setOnPageChangeListener(listener);
		mPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				showNavigation();
				return false;
			}
		});

		mPager.setAdapter(mAdapter);

	}

	private void getSettings() {

		getSettingsTask = new GetSettingsTask(this);

		getSettingsTask.setRequestCompleteListener(new RequestCompleteListener<List<SettingsBean>>() {

			@Override
			public void onSuccess(List<SettingsBean> result) {
				mApp.setSettings(result.get(0));
				mApp.getHappie_prefs().edit().putString("Settings", Common.settingsBeanToJson(mApp.getSettings())).commit();
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
					}
				});

			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			getSettingsTask.execute(mApp.getCompanyId());
		} else {
			// Toast.makeText(this, getString(R.string.no_connection),
			// Toast.LENGTH_SHORT).show();
		}
	}

	private void getOffers() {

		getOffersTask = new GetOffersTask(this);
		getOffersTask.setRequestCompleteListener(new RequestCompleteListener<List<ArticleBean>>() {

			@Override
			public void onSuccess(List<ArticleBean> result) {
				if (result != null && result.size() > 0) {
					specialOfferButton.setVisibility(View.VISIBLE);
				} else {
					specialOfferButton.setVisibility(View.GONE);
				}
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						specialOfferButton.setVisibility(View.GONE);
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
					}
				});
			}
		});

		if (Availablity.isNetworkAvailable(this)) {
			getOffersTask.execute(mApp.getCompanyId());
		} else {
			// Toast.makeText(this, getString(R.string.no_connection),
			// Toast.LENGTH_SHORT).show();
		}
	}

	private void buttonListeners() {
		orderNowButton = (Button) findViewById(R.id.btn_order_now);

		if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
			orderNowButton.setVisibility(View.VISIBLE);
		} else {
			orderNowButton.setVisibility(View.GONE);
		}
		orderNowButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Availablity.isNetworkAvailable(MenuActivity.this)) {
					Intent intent = new Intent(MenuActivity.this, CategoriesActivity.class);
					startActivityForResult(intent, 10);
				} else {
					Toast.makeText(MenuActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
				}

			}
		});
		specialOfferButton = (Button) findViewById(R.id.btn_special_offer);

		if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
			specialOfferButton.setVisibility(View.VISIBLE);
		} else {
			specialOfferButton.setVisibility(View.GONE);
		}
		specialOfferButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Availablity.isNetworkAvailable(MenuActivity.this)) {
					Intent intent = new Intent(MenuActivity.this, OffersActivity.class);
					startActivityForResult(intent, 10);
				} else {
					Toast.makeText(MenuActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
				}

			}
		});

		Button myFavorites = (Button) findViewById(R.id.btn_my_favorites);
		if (mApp.isLoggedIn()) {
			myFavorites.setVisibility(View.VISIBLE);
		} else {
			myFavorites.setVisibility(View.GONE);
		}
		myFavorites.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MenuActivity.this, MyFavoritesActivity.class);
				startActivityForResult(intent, 10);
			}
		});

		orderHistoryButton = (Button) findViewById(R.id.btn_order_history);
		// if (mApp.isLoggedIn()) {
		// orderHistoryButton.setVisibility(View.VISIBLE);
		// } else {
		// orderHistoryButton.setVisibility(View.GONE);
		// }
		orderHistoryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (Availablity.isNetworkAvailable(MenuActivity.this)) {
					(new GetHistoryTask(MenuActivity.this)).execute(mApp.getUserId());
				} else {
					Toast.makeText(MenuActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
				}

			}
		});

		Button myProfileButton = (Button) findViewById(R.id.btn_my_profile);
		if (mApp.isLoggedIn()) {
			myProfileButton.setVisibility(View.VISIBLE);
		} else {
			myProfileButton.setVisibility(View.GONE);
		}
		myProfileButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MenuActivity.this, ProfileActivity.class);
				startActivityForResult(intent, 10);
			}
		});

		Button registerButton = (Button) findViewById(R.id.btn_register);
		if (!mApp.isLoggedIn()) {
			registerButton.setVisibility(View.VISIBLE);
		} else {
			registerButton.setVisibility(View.GONE);
		}
		registerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MenuActivity.this, LoginRegisterActivity.class);
				startActivityForResult(intent, 10);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_menu, menu);
		return true;
	}

	private void footerMenuListeners() {

		linearBottom = findViewById(R.id.container_bottom_layout);

		View homeButton = findViewById(R.id.home);
		homeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

		View categoriesButton = findViewById(R.id.categories);
		categoriesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mApp.isLoggedIn()) {
					Intent intent = new Intent(MenuActivity.this, CategoriesActivity.class);
					startActivityForResult(intent, 10);
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
				}
			}
		});

		View basketButton = findViewById(R.id.basket);
		basketButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (mApp.isLoggedIn()) {
					Intent intent = new Intent(MenuActivity.this, BasketActivity.class);
					startActivityForResult(intent, 10);
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
				}
			}
		});

		View searchButton = findViewById(R.id.search);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		switch (resultCode) {

		case 200:
			Intent intent = new Intent(MenuActivity.this, CategoriesActivity.class);
			startActivityForResult(intent, 10);
			break;

		case 500:
			mApp.setPosition(0);
			if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
				mApp.setCompanyId(mApp.getFavorites().get(mApp.getPosition()).getCompanyId());
				navigation.setCount(mApp.getFavorites().size());
				navigation.setPos(mApp.getPosition());
			} else {
				navigation.setCount(0);
				navigation.setPos(mApp.getPosition());
			}
			mAdapter.notifyDataSetChanged();

			buttonsVisiblity();

			break;

		case 600:
			mApp.setPosition(0);
			if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
				mApp.setCompanyId(mApp.getFavorites().get(mApp.getPosition()).getCompanyId());
				navigation.setCount(mApp.getFavorites().size());
				navigation.setPos(mApp.getPosition());
			} else {
				navigation.setCount(0);
				navigation.setPos(mApp.getPosition());
			}
			navigation.setCount(mApp.getFavorites().size());
			navigation.setPos(mApp.getPosition());
			mAdapter.notifyDataSetChanged();

			buttonListeners();

			Toast.makeText(this, getString(R.string.logged_out_successfully), Toast.LENGTH_SHORT).show();

			break;

		case 800:
			mApp.setPosition(0);
			if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
				mApp.setCompanyId(mApp.getFavorites().get(mApp.getPosition()).getCompanyId());
				navigation.setCount(mApp.getFavorites().size());
				navigation.setPos(mApp.getPosition());
			} else {
				navigation.setCount(0);
				navigation.setPos(mApp.getPosition());
			}
			mAdapter.notifyDataSetChanged();
			buttonListeners();

			Toast.makeText(this, getString(R.string.logged_in_successfully), Toast.LENGTH_SHORT).show();

			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void buttonsVisiblity() {
		orderNowButton.setVisibility(View.GONE);
		specialOfferButton.setVisibility(View.GONE);
		orderHistoryButton.setVisibility(View.GONE);

		if (mApp.getFavorites() != null && mApp.getFavorites().size() > 0) {
			orderNowButton.setVisibility(View.VISIBLE);
		}

		// if (mApp.isLoggedIn()) {
		// orderHistoryButton.setVisibility(View.VISIBLE);
		// }
	}

	@Override
	protected void onDestroy() {
		if (getSettingsTask != null) {
			getSettingsTask.setRequestCompleteListener(null);
		}

		if (getOffersTask != null) {
			getOffersTask.setRequestCompleteListener(null);
		}

		mApp.setPosition(0);
		if (mApp.getFavorites() != null) {
			mApp.getFavorites().clear();
			mApp.getHappie_prefs().edit().putString("Favorites", "[]").commit();
		}

		if (mApp.getBasketList() != null) {
			mApp.getBasketList().clear();
			mApp.getHappie_prefs().edit().putString("BasketList", "[]").commit();
		}

		super.onDestroy();
	}

	private Handler hideHandler = new Handler();
	private Runnable hideControllerThread = new Runnable() {

		public void run() {
			navigation.setVisibility(View.GONE);
		}
	};

	public void hideNavigation() {
		hideHandler.postDelayed(hideControllerThread, 3000);
	}

	public void showNavigation() {
		navigation.setVisibility(View.VISIBLE);
		hideHandler.removeCallbacks(hideControllerThread);
		hideNavigation();
	}

}
